package com.ruge.test.Velocity;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.junit.*;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * 爱丽丝、如歌  创建于 2018/7/11 19:35
 * 说明:  TODO
 */
public class VelocityModelGenerator {
    private static Connection conn = null;
    private static List<VelocityModelTable> tables = null;
    private static List<VelocityModelField> fields = null;
    private static VelocityModelCustom custom = null;

    @BeforeClass
    public static void test1() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ruge_security?serverTimezone=UTC", "root", "root");
        } catch (Exception e) {
            System.out.println("数据库连接失败");
            e.printStackTrace();
        }
    }

    @Before
    public void test2() {
        custom = new VelocityModelCustom();
        custom.setPackageName("com.ruge.test");
        custom.setPackageImport(Arrays.asList(
                "lombok.AllArgsConstructor;",
                "lombok.Data;",
                "lombok.NoArgsConstructor;"
        ));
        custom.setPackageAuthor("爱丽丝、如歌");
        custom.setPackageDate("2018年7月11日20:17:30");
    }

    @Test
    public void test3() {
        QueryRunner runner = new QueryRunner();
        Object[] params = {"sys_user"};
        try {
            /**
             * show table status where name = 'sys_user';
             * 首先查询出表信息
             */
             tables = runner.query(conn, "show table status where name = ? ", new BeanListHandler<VelocityModelTable>(VelocityModelTable.class), params);
            /**
             * 查询表结构
             */
            String sql = "show full fields from  sys_log";
            fields = runner.query(conn, sql, new BeanListHandler<VelocityModelField>(VelocityModelField.class));
            for (int i = 0; i <fields.size() ; i++) {
            VelocityModelFieldType type = new VelocityModelFieldType();
                UnderlineToCamel camel = new UnderlineToCamel();
                String fileType = fields.get(i).getType();
                String fieldName = fields.get(i).getField();
                fileType = type.get(fileType);
                fieldName = camel.underline2Camel(fieldName,true);
                fields.get(i).setType(fileType);
                fields.get(i).setField(fieldName);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @After
    public void test4() throws IOException {
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.init();
        VelocityContext context = new VelocityContext();
        context.put("tables", tables);
        context.put("fields", fields);
        System.out.println(fields);
        context.put("package", custom);
        String str = "velocity/Velocity_model.vm";
        Template template = velocityEngine.getTemplate(str);

        File saveFile = new File("F:test.java");

        //创建文件输出流
        FileOutputStream outStream = new FileOutputStream(saveFile);
        //因为模板整合的时候，需要提供一个Writer，所以创建一个Writer
        OutputStreamWriter writer = new OutputStreamWriter(outStream);
        //创建一个缓冲流
        BufferedWriter bufferWriter = new BufferedWriter(writer);

        template.merge(context, bufferWriter);
        //强制刷新
        bufferWriter.flush();//强制刷新
        outStream.close();
        bufferWriter.close();
    }

    @AfterClass
    public static void test5() {
        try {
            DbUtils.close(conn);
        } catch (SQLException e) {
            System.out.println("数据库关闭失败");
            e.printStackTrace();
        }
    }
}
